/*
 * @Author: 陈攀
 * @Date: 2021-05-21 15:00:39
 * @LastEditTime: 2021-07-29 15:44:01
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /base-framework-web/src/layouts/BasicLayout.tsx
 */
import React, { useState, useEffect } from 'react';
import { UserOutlined } from '@ant-design/icons';
import { Avatar, Breadcrumb, Menu } from 'antd';
import type { BasicLayoutProps, MenuDataItem } from '@ant-design/pro-layout';
import { SettingOutlined } from '@ant-design/icons';
import { connect } from 'dva';
import 'remixicon/fonts/remixicon.css';
import { getUserInfo } from '@/services/userControl';
import { getUserMessage } from '@/services/common';
import { loginOut } from '@/services/login';
import { Dropdown } from 'antd';
import { CaretDownOutlined } from '@ant-design/icons';

import ProLayout from '@ant-design/pro-layout';
import { NavLink, history } from 'umi';
import { setStorageData } from '@/utils/tools';
import './index.less';

interface IUserInfo {
  employeeName: string;
}

const BasicLayout = (props: any) => {
  const {
    location: { pathname },
    getStatusMap,
    menuData,
  } = props;
  const [breadcrumbMenu, setBreadcrumbMenu] = useState([]);
  const [userInfo, setUserInfo] = useState<IUserInfo>();
  useEffect(() => {
    getStatusMap('sys_common_status');
  }, []);

  //获取用户信息
  useEffect(async () => {
    getUserInfo().then((res) => {
      // 用户信息本地缓存
      localStorage.setItem('user', JSON.stringify(res.data));
      setUserInfo(res.data);
    });
    const res = await getUserMessage();
    setStorageData('userInfo', res?.data);
  }, []);

  const handleLogout = () => {
    loginOut().then((res) => {
      const { code } = res;
      code === 200 && history.push('/features/login');
      // 清空user信息缓存
      localStorage.removeItem('user');
    });
  };

  const userMes = (
    <div className="userInfo">
      <span onClick={handleLogout}>退出登录</span>
    </div>
  );
  // 处理菜单中的icon
  const loopMenuItem = (menus: MenuDataItem[]): MenuDataItem[] =>
    menus.map(({ icon, children, ...item }) => ({
      ...item,
      // icon: icon && <i className={`${icon} ant-menu-item-icon`} style={{ verticalAlign: "bottom" }}></i>,
      // todo 为了方便测试查看，加上一个默认的图标。 想要正常流程显示的图标。使用上一行注释的代码
      icon: (
        <i
          className={`ri-apps-fill ant-menu-item-icon`}
          style={{ verticalAlign: 'bottom' }}
        ></i>
      ),
      children: children && loopMenuItem(children),
    }));

  const _settingProps: BasicLayoutProps = {
    // route: {
    //   routes: menuData,
    // },
    location: {
      pathname,
    },
    navTheme: 'light',
    fixSiderbar: true,
    layout: 'mix',
    fixedHeader: true,
    title: '公共模块',
    logo: 'https://gw.alipayobjects.com/zos/antfincdn/PmY%24TNNDBI/logo.svg',
    menuItemRender: (item: any, dom) => <NavLink to={item.path}>{dom}</NavLink>,
    menu: { request: async () => loopMenuItem(menuData) },
  };

  return (
    <ProLayout
      {..._settingProps}
      // contentStyle={{margin:"0px"}}
      disableContentMargin
      // 自定义头内容的方法
      headerContentRender={(headProps: any) => {
        let breadcrumb = headProps.breadcrumb; // 获取的所有的路由信息
        let matchMenuKeys = headProps.matchMenuKeys; // 当前路由的关键字
        let breadcrumbDataArr = []; //面包屑相关的路由数组
        for (const key in matchMenuKeys) {
          if (Object.prototype.hasOwnProperty.call(matchMenuKeys, key)) {
            const element = matchMenuKeys[key];
            breadcrumbDataArr.push(breadcrumb[element]);
          }
        }
        sessionStorage.setItem(
          'breadcrumbDataArr',
          JSON.stringify(breadcrumbDataArr),
        );
        return (
          <div style={{ display: 'inline-block' }}>
            <Breadcrumb>
              {breadcrumbDataArr?.map((item, index) => {
                return (
                  <Breadcrumb.Item key={item.key}>{item.name}</Breadcrumb.Item>
                );
              })}
            </Breadcrumb>
          </div>
        );
      }}
      // 自定义头右部的 render 方法
      rightContentRender={() => {
        return (
          <div>
            <Dropdown
              overlay={userMes}
              trigger={['click']}
              placement={'topCenter'}
            >
              <a
                className="ant-dropdown-link"
                onClick={(e) => e.preventDefault()}
              >
                <Avatar shape="square" size="small" icon={<UserOutlined />} />
                &nbsp;&nbsp;
                <span className="name">{userInfo?.employeeName}</span>
                <CaretDownOutlined />
              </a>
            </Dropdown>
          </div>
        );
      }}
    >
      {props.children}
    </ProLayout>
  );
};
//暂时BasicLayout获取字典 后期移步到登录接口一并获取
const mapDispatchToProps = (dispatch: any) => {
  return {
    getStatusMap(params: string) {
      dispatch({
        type: 'common/getStatusMap',
        payload: params,
      });
    },
  };
};
export default connect(null, mapDispatchToProps)(BasicLayout);
